﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class CloudCardsController : BaseController
    {
        #region 列表
        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Listing(int draw, int start, int length, string keyWord = "", int cateId = 0, int status = -1)
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                var direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "CardName", "CardCategoryId", "PassStatus" };
                var list = CloudCardsBLL.Instance.GetPagingList(draw, (start/length) + 1, length, SqlSafe(keyWord), cateId, status, CurrentUser.ShopId.ToString(), orderByColumns[order] + " " + direction);
                return Json(list);
            }
            catch (Exception ex)
            {
                Logger.Error("CloudCards Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }
        #endregion

        #region 创建
        public ActionResult Create()
        {
            InitiSet();
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, CloudCards model)
        {
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var cate = CardCategoryBLL.Instance.GetModel(model.CardCategoryId);
            if (cate == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var strUploadImage = UploadImage("fileImage", "/CloudCards/Logo/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage))
            {
                model.LoGo = strUploadImage;
            }
            model.CategoryCode = cate.CategoryCode;
            model.CardKey = CommonHelper.GetGuidKey();
            model.AddTime = DateTime.Now;
            model.PassTime = DateTime.Now;
            model.AddUserId = CurrentUser.AccountId;
            model.PassStatus = (int)CloudCardEnum.CloudCardsPassStatus.待审核;
            model.ShopId = CurrentUser.ShopId;
            if (model.CategoryCode == "1002")
            {
                model.DiscountValue = 0;
            }
            else if (model.CategoryCode == "1003")
            {
                model.ReduceCost = 0;
            }
            else
            {
                model.LeastCost = 0;
                model.ReduceCost = 0;
                model.DiscountValue = 0;
            }
            if (CurrentUser.IsHeadquarters)
            {
                model.UsableShopIds = !string.IsNullOrEmpty(model.UsableShopIds) ? model.UsableShopIds.Trim(',') : null;
            }
            else
            {
                model.UsableShopIds = null;
            }
            //特殊店铺用于发送平台券
            var platformShopIds = ConfigurationManager.AppSettings["PlatformShopIds"];
            if (!string.IsNullOrEmpty(platformShopIds) && platformShopIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(CurrentUser.ShopId.ToString()))
            {
                model.DisabledSeparatedIndustryIds = !string.IsNullOrEmpty(model.DisabledSeparatedIndustryIds) ? model.DisabledSeparatedIndustryIds.Trim(',') : null;
            }
            else
            {
                model.DisabledSeparatedIndustryIds = null;
            }
            var newId = CloudCardsBLL.Instance.Add(model);
            if (newId > 0)
            {
                return RedirectToAction("List");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 修改
        public ActionResult Update(int id)
        {
            if (id <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var model = CloudCardsBLL.Instance.GetModel(id);
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            var cate = CardCategoryBLL.Instance.GetModel(model.CardCategoryId);
            if (cate != null)
            {
                model.CategoryName = cate.CategoryName;
            }
            InitiSet();
            ViewBag.theHeadPic = ConfigurationManager.AppSettings["ImgFileSitePath"] + model.LoGo;
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, CloudCards model)
        {
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var tempModel = CloudCardsBLL.Instance.GetModel(model.Id);
            if (tempModel == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var strUploadImage = UploadImage("fileImage", "/CloudCards/Logo/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage))
            {
                model.LoGo = strUploadImage;
            }
            tempModel.LoGo = model.LoGo;
            tempModel.EndTime = model.EndTime;
            tempModel.ShowOnHomepage = model.ShowOnHomepage;
            if (CurrentUser.IsHeadquarters)
            {
                tempModel.UsableShopIds = !string.IsNullOrEmpty(model.UsableShopIds) ? model.UsableShopIds.Trim(',') : null;
            }
            else
            {
                tempModel.UsableShopIds = null;
            }
            //特殊店铺用于发送平台券
            var platformShopIds = ConfigurationManager.AppSettings["PlatformShopIds"];
            if (!string.IsNullOrEmpty(platformShopIds) && platformShopIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(CurrentUser.ShopId.ToString()))
            {
                tempModel.DisabledSeparatedIndustryIds = !string.IsNullOrEmpty(model.DisabledSeparatedIndustryIds) ? model.DisabledSeparatedIndustryIds.Trim(',') : null;
            }
            else
            {
                tempModel.DisabledSeparatedIndustryIds = null;
            }
            if (CloudCardsBLL.Instance.Update(tempModel))
            {
                return RedirectToAction("List");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }
        #endregion

        #region 删除
        [HttpPost]
        public JsonResult Delete()
        {
            var result = CloudCardsBLL.Instance.DeleteList(Request["doIds"]);
            return Json(result);
        }
        #endregion

        #region 其他
        private void InitiSet()
        {
            var canShare = new List<SelectListItem>
            {
                new SelectListItem { Value = "true", Text = "是" },
                new SelectListItem { Value = "false", Text = "否" }
            };
            ViewBag.CanShare = canShare;
            var showOnHomepage = new List<SelectListItem>
            {
                new SelectListItem { Value = "true", Text = "是" },
                new SelectListItem { Value = "false", Text = "否" }
            };
            ViewBag.ShowOnHomepage = showOnHomepage;
        }

        /// <summary>
        /// 获取细分行业列表
        /// </summary>
        [HttpPost]
        public JsonResult GetSeparatedIndustryList(string keyWords)
        {
            return Json(IndustryBLL.Instance.GetListByKeyWord(keyWords, 2));
        }
        #endregion
    }
}
